﻿// My methods here.
//-----------------------------------------------------------------------
// <Copyright file=KhuyenMai company=DHPD>
// Copyright (c) DHPD Corporation (http://dhpd.edu.vn). All rights reserved.
// </copyright>
// <author>HP</author>
//-----------------------------------------------------------------------


using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Mvc;
using KM.BUS;
using KM.ENT;
using KM.Models;
using CORE;
using HtmlAgilityPack;
using System.Linq;
using System.Threading;
using System.Net;
using System.IO;
using System.Text.RegularExpressions;
using System.Text;
using System.Collections.Specialized;
using System.Xml;
using System.Threading.Tasks;

namespace KM.Areas.Admin.Controllers
{
    public class KhuyenMaiController : Controller
    {
        int pageSize = 150;
        public ActionResult Index()
        {
            string a = Utils.getStringSession("a");
            ViewBag.a = a;
            return View();
        }
        public ActionResult dsKhuyenMai()
        {
            //lay danh sach loai san pham
            busKhuyenMai busKM = new busKhuyenMai();
            List<entKhuyenMai> lst = new List<entKhuyenMai>();
            PagingInfoModel page = new PagingInfoModel()
            {
                CurrentPage = Utils.getIntQuery("page") == 0 ? 1 : Utils.getIntQuery("page"),
                recordPerPage = pageSize
            };
            lst = busKM.getAll(ref page);
            ViewBag.page = page;
            return View(lst);
        }

        public ActionResult dsKhuyenMaiByForeignKey(int Id)
        {
            //lay danh sach loai san pham
            busKhuyenMai busKM = new busKhuyenMai();
            List<entKhuyenMai> lst = new List<entKhuyenMai>();
            PagingInfoModel page = new PagingInfoModel()
            {
                CurrentPage = Utils.getIntQuery("page") == 0 ? 1 : Utils.getIntQuery("page"),
                recordPerPage = pageSize
            };
            lst = busKM.getAllByForeignKey(Id, Constants.TRANGTHAICHO, ref page);
            ViewBag.page = page;
            return View(lst);
        }

        public ActionResult edit(int Id = 0)
        {
            busKhuyenMai busKM = new busKhuyenMai();
            entKhuyenMai entKM = new entKhuyenMai();
            entKM = busKM.getInfo(Id);
            return View(entKM);
        }

        public ActionResult delete(int Id)
        {
            busKhuyenMai busKM = new busKhuyenMai();
            busKM.delete(Id, 1);
            return RedirectToAction("dsKhuyenMai", null, new { Id = 1 });
        }
        [HttpPost]

        [ValidateInput(false)]
        public ActionResult edit(entKhuyenMai entKM)
        {
            if (!ModelState.IsValid)
            {
                return View(entKM);
            }

            busKhuyenMai busKM = new busKhuyenMai();
            busKM.createEdit(entKM);
            return RedirectToAction("edit", new { Id = entKM.KhuyenMaiId });


        }


        #region ==lay khuyen mai danh cho admin
        public static string GetWebPageHtmlFromURL(string url)
        {
            if (url == null)
            {
                url = "http://www.hmsa.com/portal/provider/zav_pel.aa.COD.700.htm";
            }


            WebClient webClient = new WebClient();
            webClient.Encoding = Encoding.UTF8;

            CookieContainer cookies = new CookieContainer();
            string page = webClient.DownloadString(url);
            return page;

        }

        public static string sendGetRequest(string url)
        {
            string a = "";
            Thread thread = new Thread(delegate()
            {
                using (System.Windows.Forms.WebBrowser browser = new System.Windows.Forms.WebBrowser())
                {
                    browser.Navigate(url);


                    while (browser.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete)
                    {
                        System.Windows.Forms.Application.DoEvents();
                    }



                    a = browser.DocumentText;
                    FileTool.Log(a);
                }
            });
            thread.SetApartmentState(ApartmentState.STA);
            thread.Start();
            thread.Join();
            return a;

        }
        

        public ActionResult GetToalSucces()
        {
            ViewBag.me = Utils.getStringSession("k");
            return View();
        }
        public ActionResult GetProduct(int Id)
        {


            InsertKM(Id);

            return RedirectToAction("InsertProduct", new { Id = Id});
        }
        #region==lay khuyen mai bang phuong thuc post===
        [HttpPost]
        public ActionResult GetProduct(FormCollection collection)
        {
            //http://remthinhphat.com/rem-vai.html?page=1

            int k = 0;
            string site = collection["site"].ToString();
            string url = collection["Url"].ToString();
            string divkm = collection["divkm"].ToString();
            string nodeName = collection["nodeName"].ToString();
            string nodeImage = collection["nodeImage"].ToString();
            string nodeImageAttributes = collection["nodeImageAttributes"].ToString();
            string nodeLink = collection["nodeLink"].ToString();//div[@class=\"thumb\"]/a
            string nodeLinkAttributes = collection["nodeLinkAttributes"].ToString();
            string nodeGiaNiemYet = collection["nodeGiaNiemYet"].ToString();
            string nodeGiaKM = collection["nodeGiaKM"].ToString();
            string nodeThoiGian = collection["nodeThoiGian"].ToString();
            HtmlWeb htmlWeb = new HtmlWeb();
            // Creates an HtmlDocument object from an URL
            HtmlAgilityPack.HtmlDocument document = htmlWeb.Load(url);
            var nodes = from foo in document.DocumentNode.Descendants("div")
                        where foo.Attributes["class"] != null && foo.Attributes["class"].Value.Contains(divkm)
                        select foo;
            int i = 1;
            string a = "";

            entKhuyenMai entKM;
            if (nodes != null)
            {
                //lay doi dung
                List<entKhuyenMai> lstNew = new List<entKhuyenMai>();
                busKhuyenMai busKM = new busKhuyenMai();
                string link = "";
                foreach (HtmlAgilityPack.HtmlNode item in nodes)
                {
                    HtmlNode Link = item.SelectSingleNode(nodeLink);
                    if (busKM.checkLink(site + Link.Attributes[nodeLinkAttributes].Value))
                    {
                        HtmlNode img = item.SelectSingleNode(nodeImage);
                        string filename = DateTime.Now.ToString("ddmmyyhhmmss").ToString() + k++.ToString() + ".jpg";
                        if (img != null)
                        {
                            // Utils.DownloadImageFromUrl(img.Attributes["src"].Value, filename);

                            HtmlNode Name = item.SelectSingleNode(nodeName);
                            HtmlNode GiaNiemYet = item.SelectSingleNode(nodeGiaNiemYet);
                            HtmlNode GiaKM = item.SelectSingleNode(nodeGiaKM);
                            HtmlNode ThoiGian = item.SelectSingleNode(nodeThoiGian);

                            entKM = new entKhuyenMai();
                            entKM.KhuyenMaiId = i;
                            entKM.TieuDe = Name.InnerText;
                            entKM.ImageSmall = img.Attributes[nodeImageAttributes].Value;
                            entKM.Link = Link.Attributes[nodeLinkAttributes].Value;
                            entKM.GiaNiemYet = int.Parse(GiaNiemYet.InnerText.Replace(",", "").Replace("đ", ""));
                            entKM.GiaKM = int.Parse( GiaKM.InnerText.Replace(",", "").Replace("đ", ""));
                            entKM.ThoiGian = ThoiGian.InnerText;
                            i++;

                            //a += Name.InnerText;

                        }
                    }

                }

            }

            //lay doi dung


            //duyet loai nhung km đã có trong database dua vao truong link
            //                    HtmlAgilityPack.HtmlDocument document2 = htmlWeb.Load(item.Link);
            //  item.Summary = document2.DocumentNode.SelectSingleNode("//*[@id='product-description']").InnerHtml;



            //duyet loai nhung km đã có trong database dua vao truong link
            //  HtmlAgilityPack.HtmlDocument document2 = htmlWeb.Load(item.Link);
            // item.Summary = document2.DocumentNode.SelectSingleNode("//*[@id='product-description']").InnerHtml;
            // a = string.Format("insert into SanPham(tieude,link,Summary) values(N'{0}','{1}',{2})", item.TieuDe, item.Link, item.Summary);
            //  FileTool.Log(a);

            return RedirectToAction("InsertProduct");

        }

        #endregion
        public ActionResult InsertProduct(int Id)
        {

            InsertKM(Id);
            List<entKhuyenMai> lst = new List<entKhuyenMai>();
            
            return View(lst);
        }

        public ActionResult InsertAll()
        {
            List<entWeb> lst = new List<entWeb>();
            busWeb busW = new busWeb();
            lst = busW.getAllWebChild();
            int i = 0;
            string a = "";
            foreach (var item in lst)
            {
                
                InsertKM(item.Id);
                i++;

            }

            ViewBag.me = i;
            return View();
        }

        public ActionResult Ajax(int Id)
        {
            GetProductConten(Id);
            ViewBag.me = Id;
            return View();
        }
        public void InsertKM( int id)
        {
            
            entWeb entW = new entWeb();
            busWeb busW = new busWeb();
            entW = busW.getInfo(id);
            string html = "";
            //lay source html theo 1 trong 2 cach
            try
            {
                html = GetWebPageHtmlFromURL(entW.Url);
            }
            catch (Exception)
            {


            }

            if (html == "")
            {
                html = sendGetRequest(entW.Url);
            }

            HtmlWeb htmlWeb = new HtmlWeb();
            htmlWeb.AutoDetectEncoding = false;


            HtmlAgilityPack.HtmlDocument document = new HtmlDocument();// htmlWeb.Load("http://muachung.vn/danh-muc/c-13/thoi-trang-nu.html");
            document.LoadHtml(html);

            var nodes = document.DocumentNode.SelectNodes(entW.RootDiv);
            entKhuyenMai entKM;
            //if (nodes != null)
            //{
            //lay doi dung
            List<entKhuyenMai> lstNew = new List<entKhuyenMai>();
            busKhuyenMai busKM = new busKhuyenMai();
            int k2 = 0;
            string link = "";
            int k = 0;
            foreach (HtmlAgilityPack.HtmlNode item in nodes)
            {

                //ViewBag.me = item.InnerText;
                //return View();
                //try
                //{
                HtmlNode Link = item.SelectSingleNode(entW.NodeLink);


                //chek neu link la duong dan không phai la duong dan tuyen doi thi  them site vao
                link = Link.Attributes[entW.NodeLinkAttribute].Value;

                if (link.IndexOf(entW.SiteUrl) < 0)
                {
                    link = entW.SiteUrl + Link.Attributes[entW.NodeLinkAttribute].Value;

                }

                if (busKM.checkLink(link))
                {
                    entKM = new entKhuyenMai();
                    HtmlNode img = item.SelectSingleNode(entW.NodeImage);
                    string filename = DateTime.Now.ToString("ddmmyyhhmmss").ToString() + k++.ToString() + ".jpg";
                    if (img != null)
                    {
                        //ViewBag.me = img.Attributes["data-original"].Value;

                        try
                        {
                            //Utils.DownloadImageFromUrl(img.Attributes[entW.NodeImageAttribute].Value, filename);
                            entKM.ImageSmall = img.Attributes[entW.NodeImageAttribute].Value;
                        }
                        catch (Exception)
                        {
                            entKM.ImageSmall = img.Attributes["src"].Value;
                            //Utils.DownloadImageFromUrl(img.Attributes["src"].Value, filename);
                        }


                        HtmlNode Name = item.SelectSingleNode(entW.NodeName);
                        HtmlNode GiaNiemYet = item.SelectSingleNode(entW.NodeGiaNiemYet);
                        HtmlNode GiaKM = item.SelectSingleNode(entW.NodeGiaKM);
                        try
                        {
                            HtmlNode ThoiGian = item.SelectSingleNode(entW.NodeThoiGian);
                            string[] thoigian = ThoiGian.InnerText.Split(':');
                            DateTime dt = DateTime.Now;
                            if (ThoiGian.InnerText.Split(':').Length - 1 == 3)
                            {
                                dt = dt.AddHours(int.Parse(thoigian[0]));
                                dt = dt.AddMinutes(int.Parse(thoigian[1]));
                                dt = dt.AddSeconds(int.Parse(thoigian[2]));
                            }
                            else if (ThoiGian.InnerText.Split(':').Length - 1 == 2)
                            {
                                dt = dt.AddMinutes(int.Parse(thoigian[0]));
                                dt = dt.AddSeconds(int.Parse(thoigian[1]));
                            }
                            entKM.ThoiGian = dt.ToString();
                        }
                        catch (Exception)
                        {


                        }

                        try
                        {
                            //  entKM.KhuyenMaiId = i;
                            entKM.TieuDe = WebUtility.HtmlDecode(Name.InnerText);


                            //entKM.ImageSmall = filename;
                            entKM.Link = link;

                            entKM.GiaNiemYet = int.Parse(GiaNiemYet.InnerText.Split('đ')[0].Replace(",", "").Replace("đ", "").Replace(".", "").Replace(" ", ""));


                            entKM.GiaKM = int.Parse(GiaKM.InnerText.Split('đ')[0].Replace(",", "").Replace("đ", "").Replace(".", "").Replace(" ", "").Replace("&nbsp;", ""));
                            entKM.NguoiSua = 1;
                            entKM.WebId = entW.Id;
                            entKM.ThanhPho = entW.ThanhPho;
                            entKM.TrangThai = Constants.TRANGTHAIDUYET;


                            k2++;
                            lstNew.Add(entKM);
                            busKM.createEdit(entKM, entW.LoaiKhuyenMaiId);
                        }
                        catch (Exception)
                        {


                        }


                    }
                }

                //catch (Exception)
                //{
                //    throw;
                //}

            }
        }
        [HttpPost]
        public ActionResult Ajax(FormCollection collection)
        {
            ViewBag.me = 1;
            int Id = int.Parse(collection["id"].ToString());
            busKhuyenMai busKM = new busKhuyenMai();
            //lay duong dan anh de xoa
            entKhuyenMai entKM = new entKhuyenMai();
            entKM = busKM.getInfo(Id);
            try
            {
                if (System.IO.File.Exists(Server.MapPath("/images/" + entKM.ImageSmall)))
                {
                    System.IO.File.Delete(Server.MapPath("/images/" + entKM.ImageSmall));

                }
                busKM.delete(Id, 1);
            }
            catch (Exception)
            {

                ViewBag.me = 0;
            }

            return View();
        }
        public ActionResult AjaxInsert(int Id)
        {
            busKhuyenMai busKM = new busKhuyenMai();
            return View();
        }
        #region ===lấy nội dung và thời gian===
        public void GetProductConten(int Id)
        {

            entKhuyenMai entKM = new entKhuyenMai();
            busKhuyenMai busKM = new busKhuyenMai();
            entKM = busKM.getInfo(Id);
            //string html = "";
            ////lay source html theo 1 trong 2 cach
            //try
            //{
            //    html = GetWebPageHtmlFromURL(entKM.Link);
            //}
            //catch (Exception)
            //{


            //}

            //if (html == "")
            //{
            //    html = sendGetRequest(entKM.Link);
            //}
            //HtmlWeb htmlWeb = new HtmlWeb();
            //htmlWeb.AutoDetectEncoding = false;


            //HtmlAgilityPack.HtmlDocument document = new HtmlDocument();// htmlWeb.Load("http://muachung.vn/danh-muc/c-13/thoi-trang-nu.html");
            //document.LoadHtml(html);
            //entWeb entW = new entWeb();
            //busWeb busW = new busWeb();
            //entW = busW.getInfo(entKM.WebId);
            //var nodes = document.DocumentNode.SelectSingleNode(entW.NodeNoiDung);
            //entKM.Summary = nodes.InnerHtml;
            entKM.TrangThai = Constants.TRANGTHAIDUYET;
            busKM.createEdit(entKM);
            

        }
        #endregion

        #endregion

        public ActionResult DanhSachKhuyenMai(int id)
        {
            byte trangthai =Constants.MYKHUYENMAI;
            List<entKhuyenMai> lst = new List<entKhuyenMai>();
            busKhuyenMai busKM = new busKhuyenMai();

            PagingInfoModel page = new PagingInfoModel()
            {
                CurrentPage = Utils.getIntQuery("page") == 0 ? 1 : Utils.getIntQuery("page"),
                recordPerPage = 18
            };

            lst = busKM.getAllByForeignKey(id, trangthai, ref page, Constants.MYKHUYENMAI);
            ViewBag.page = page;
            ViewBag.id = id;
            return View(lst);
        }



    }
}

